<?php 

Class ModuleResultOfSignUp extends CmsCustomModule {

    private function setHeadString($condition=null,$sort_by=null,$rand_code) {
        $date_list = null;
        $remark_list = null;
        $current_time = date('Y-m-d H:i:s');
        $region_country_list = ' NONE ';
        
        if (!empty($condition) && is_array($condition)) {

            //date time.
            if (isset($condition['play_time']['start_date']) && isset($condition['play_time']['end_date'])) {
                $date_list = '<strong>By Date: </strong>&nbsp; <b>From</b> '.$condition['play_time']['start_date'].' <b>To</b> '.$condition['play_time']['end_date'];
            }
            else {
                $date_list = '<b>By Month: </b>&nbsp;'.$condition['play_time']['start_month'].' <b>To</b> '.$condition['play_time']['end_month'];
            }

            //region & country
            if (!empty($condition['country_code'])) {
                $country_arr = $condition['country_code'];
                $region_country_list = AC::getInstance()->getCountryListToHeader($country_arr);
            }
            
        }
        
        //remark setting.

        $remark_list =    '<table class="nob">'.
                          '    <colgroup><col width="30"/><col width="" /><col width="30"/><col width=""/></colgroup>'.
                          '    <tr><td colspan="4"><b>Remark</b>:</td></tr>'.
                          '    <tr>'.
                          '         <td>FM_S1: </td><td> Free Membership Registration - Fill In The Form</td>'.
                          '         <td>P_S1: </td><td> Premium - Select Plan</td>'.
                          '    </tr>'.
                          '     <tr>'.
                          '         <td>FM_A: </td><td> Free Membership - Activate Complete</td>'.
                          '         <td>P_S2: </td><td> Premium - Personal Details</td>'.
                          '     </tr>'.
                          '     <tr>'.
                          '         <td>FB_S1: </td><td> Facebook - Fill In The Form</td>'.
                          '         <td>P_S3: </td><td> Premium - Payment</td>'.
                          '     </tr>'.
                          '     <tr>'.
                          '         <td>FB_S2: </td><td> Facebook - Personal Details</td>'.
                          '         <td>P_S4: </td><td> Premium - Confirmation</td>'.
                          '     </tr>'.
                          '     <tr>'.
                          '         <td>FB_A: </td><td> Facebook - Activate Complete</td>'.
                          '         <td>P_A: </td><td>Premium - Activate Complete</td>'.
                          '     </tr>'.
                          '</table>';


        //sub condition.
        $condition_list = '<br/>'.
                          '<div>'.$date_list.'</div>'.
			              '<table class="nob">'.
                          '<tr>'.
                          ' <td valign="top" width="110">'.
                          '     <b class="tit">Region/Country: </b>&nbsp;</td>'.
                          ' <td valign="top">'.$region_country_list.'</td>'.
                          '</tr>'.
                          '</table>'.
                          '<div>&nbsp;</div>'.$remark_list;
        //control tag.                         
        $export_tag =  'Export to '.AC::exportHtmlControl($rand_code,AC::EXPORT_FILE_PREFIX_NAME_SIGN_UP)
                                   .AC::exportPdfControl($rand_code,AC::EXPORT_FILE_PREFIX_NAME_SIGN_UP)
                                   .AC::exportCvsControl($rand_code,AC::EXPORT_FILE_PREFIX_NAME_SIGN_UP);
        
        //output view string.
        $head_string = '<div class="hd">'.
                       '    <div class="utility">'.
                       '        <a href="#" class="print">Print</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.$export_tag.
                       '    </div>'.
                       '    <hr>'.
                       '    <h1>'.$this->title.'</h1>'.
                       '    <div class="ui-helper-clearfix">'.
                       '        <div class="time">'.$current_time.'</div>'.
                       '        <ul>'.$condition_list.'</ul>'.
                       '    </div>'.
                       '</div>';

        //output export string.
        $head_string_exprot = '<div class="hd">'.
                                '    <div class="utility">'.
                                '        <a href="#" class="print">Print</a> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'.
                                '    </div>'.
                                '    <hr>'.
                                '    <h1>'.$this->title.'</h1>'.
                                '    <div class="ui-helper-clearfix">'.
                                '        <div class="time">'.$current_time.'</div>'.
                                '        <ul>'.$condition_list.'</ul>'.
                                '    </div>'.
                                '</div>';

        return array('view'=>$head_string,'export'=>$head_string_exprot);
    }
    
    //get the page search filter condition.
    private function getPageCondition($params) {
        $date = array();
        if (!empty($params['startdate']) && !empty($params['enddate'])) {
            $date['start_date'] = $params['startdate'];
            $date['end_date'] = $params['enddate'];
            if ($params['enddate']<$params['startdate']) $date['end_date'] = date('Y-m-d');
        }

        $month = array();
        if (!empty($params['startmonth']) && !empty($params['endmonth'])) {
            $month['start_month'] = $params['startyear'].'-'.$params['startmonth'];
            $month['end_month'] = $params['endyear'].'-'.$params['endmonth'];
        }
        $play_time = ($params['dateby']=='month') ? $month : $date;


        $country = array();
        if (!empty($params['country_code'])) {
            $country = (!empty($params['country_code'])) ? AC::getInstance()->getRegionCountryCondtion(json_decode($params['country_code'],true)) : array();
        }

        return array('condition'=>array(
                                        'play_time'=>$play_time,
                                        'country_code'=>$country));
    }

    //get the table name.
    private function getDateCondition($play_time) {
        $table_name = array();
        $date_condition = '';
        if (!empty($play_time['start_date']) && !empty($play_time['end_date'])) {
            $date_condition .= ' AND (SUBSTRING(access_datetime,1,10)>="'.$play_time['start_date'].'" AND SUBSTRING(access_datetime,1,10)<="'.$play_time['end_date'].'") ';
        }
        elseif(!empty($play_time['start_month']) && !empty($play_time['end_month'])) {
            if ($play_time['start_month']==$play_time['end_month']) {
                $table_name['year'] = date('Y',strtotime($play_time['start_month']));
                $table_name['month'] = date('m',strtotime($play_time['start_month']));
                $date_condition .= ' AND (SUBSTRING(access_datetime,1,7)="'.$table_name['year'].'-'.$table_name['month'].'") ';
            }
            else {
                $date_condition .= ' AND (SUBSTRING(access_datetime,1,7)>="'.$play_time['start_month'].'" AND SUBSTRING(access_datetime,1,7)<="'.$play_time['end_month'].'") ';
            }
        }

        return array('condition'=>$date_condition);
    }

    //out put the body string.
    private function getOutPutBody($head_string,$body_string) {
        $output ='<div id="result" class="signup_result" >'.$head_string.
                 '  <div class="bd">'.
                    $body_string.
                 '  </div>'.
                 '</div>';
        return $output;
    }

    //set the body's Title.
    private function setParagraphTitle($title) {
        return '<h2>'.$title.'</h2>';
    }

    //set the table's title
    static private function setTableHeaderTitle() {
        $body_list = null;
        $main_title_of_table = AC::$sign_up_report_title;
        $sub_title_of_table = AC::$sign_up_report_format;
        $region_country = AC::SIGN_UP_DIAGNOSTIC_TITLE_OF_REGION_COUNTRY;

        $body_list = '<tr>'.
	                 '  <td width="22%" rowspan="2" bgcolor="#eeeeee" class="txtleft">'.
                     '      <strong>'.$region_country.'</strong>'.
                     '  </td>';
        foreach($main_title_of_table as $key=>$value) {
            $colspan_num = count($sub_title_of_table[$key]);
	        $body_list .='<td colspan="'.$colspan_num.'" bgcolor="#eeeeee">'.
                         '  <div align="center">'.
                         '      <strong>'.$value.'</strong>'.
                         '  </div>'.
                         '</td>';
        }
        
        $body_list .= '</tr><tr>';
        foreach($main_title_of_table as $key=>$value) {
            //$loop_max = count($sub_title_of_table[$key]);
            foreach($sub_title_of_table[$key] as $key2=>$val2) {
                $body_list.='<td width="8%" bgcolor="#eeeeee">'.$val2.'</td>';
            }
        }
        $body_list .='</tr>';
        
        return $body_list;
    }
    
    //set the table's title of total summary.
    static private function setTableHeaderTitleByNone() {
        $body_list = null;
        $main_title_of_table = AC::$sign_up_report_title;
        $sub_title_of_table = AC::$sign_up_report_format;
        $body_list .= '<tr>';
        foreach($main_title_of_table as $key=>$value) {
            $colspan_num = count($sub_title_of_table[$key]);
	        $body_list .='<td colspan="'.$colspan_num.'" bgcolor="#eeeeee">'.
                         '  <div align="center">'.
                         '      <strong>'.$value.'</strong>'.
                         '  </div>'.
                         '</td>';
        }

        $body_list .= '</tr><tr>';
        foreach($main_title_of_table as $key=>$value) {
            //$loop_max = count($sub_title_of_table[$key]);
            foreach($sub_title_of_table[$key] as $key2=>$val2) {
                $body_list.='<td width="10%" bgcolor="#eeeeee">'.$val2.'</td>';
            }
        }
        $body_list .='</tr>';
        return $body_list;
    }

    //set the table's body.
    private function setTableBody($data,$country_code) {
        $body_list = null;
        $tmp_num_arr = array();
        $all_tmp_num_arr = array();
        $main_title_of_table = AC::$sign_up_report_title;
        $sub_title_of_table = AC::$sign_up_report_format;
        $sign_up_page_types = AC::$sign_up_page_types;
        $table_title_nums = AC::getSignUpDiagnosticTableCol();
        $num_replace_pre = 'num_total_';
        $all_num_replace_pre = 'all_num_total_';

        for($i=1;$i<=$table_title_nums;$i++) {
            $tmp_num_arr[$i] = $num_replace_pre.$i;
            $all_tmp_num_arr[$i] = $all_num_replace_pre.$i;
        }

        //get data with loop.
        $all_num_i = 1;
        foreach($country_code as $region=>$country) {
            $body_list .= '<tr class="weight">'.
	                      ' <td class="txtleft"><p>'.$region.'</p></td>';
            for($i=1;$i<=$table_title_nums;$i++) {
                $body_list .= '<td>{NUM_TOTAL_'.$i.'}</td>';
            }
            $body_list .= '</tr>';
            
            foreach($country as $code=>$country_name) {
                $body_list .= '<tr>'.
                              ' <td class="txtleft"><p>'.$country_name.' ('.$code.')</p></td>';
                $num_i = 1;
                foreach($main_title_of_table as $k1=>$val1) {
                    foreach($sub_title_of_table[$k1] as $k2=>$val2) {
                        $page_type = $sign_up_page_types[$k1];
                        $step_num = $k2;
                        $total_num = (isset($data[$code][$page_type][$step_num])) ? $data[$code][$page_type][$step_num] : 0; 
                        $body_list .= '<td>'.number_format($total_num).'</td>';
                        $num_replace = $num_replace_pre.$num_i;
                        $$num_replace = (isset($$num_replace)) ? $$num_replace+$total_num : $total_num;
                        $num_i++;
                    }
                }
                $body_list .= '</tr> ';
            }
            
            //replace the region total.
            $total_tmp_ = 0;
            foreach($tmp_num_arr as $k=>$num_list) {
                $replace_before = strtoupper("{".$num_replace_pre.$k."}");
                $replace_after = number_format($$num_list);
                $total_tmp_ = intval($$num_list);
                $body_list = str_replace($replace_before,$replace_after,$body_list);
                $$num_list = 0;

                //all num setting. add all col data.
                $all_num_replace = $all_num_replace_pre.$k;
                $$all_num_replace = (isset($$all_num_replace)) ? $$all_num_replace+$total_tmp_ : $total_tmp_;
            }
        }

        //set Total row.
        $body_list .= '<tr class="weight">'.
                      ' <td class="txtleft"><p>Total</p></td>';
        for($i=1;$i<=$table_title_nums;$i++) {
            $body_list .= '<td>{ALL_NUM_TOTAL_'.$i.'}</td>';
        }
        $body_list .= '</tr>';
        foreach($all_tmp_num_arr as $k=>$num_list_) {
            $replace_before = strtoupper("{".$all_num_replace_pre.$k."}");
            $replace_after = number_format($$num_list_);
            $body_list = str_replace($replace_before,$replace_after,$body_list);
        }
        //end.
        
        return $body_list;
    }

    //set the table's body by none.
    private function setTableBodyByNone($data) {
        $body_list = null;
        $tmp_num_arr = null;
        $main_title_of_table = AC::$sign_up_report_title;
        $sub_title_of_table = AC::$sign_up_report_format;
        $sign_up_page_types = AC::$sign_up_page_types;
        $table_title_nums = AC::getSignUpDiagnosticTableCol();
        $num_replace_pre = 'num_total_';

        //define the default var.
        for($i=1;$i<=$table_title_nums;$i++) {
            $tmp_num_arr[$i] = $num_replace_pre.$i;    
        }
        //get data with loop
        $body_list .= '<tr class="weight">';
        for ($i=1;$i<=$table_title_nums;$i++) {
            $body_list .= '<td>{NUM_TOTAL_'.$i.'}</td>';
        }
        $body_list .= '</tr>';

        $body_list .= '<tr>';
        $num_i = 1;
        foreach($main_title_of_table as $k1=>$val1) {
            foreach($sub_title_of_table[$k1] as $k2=>$val2) {
                $total_num = 0;
                $page_type = $sign_up_page_types[$k1];
                $step_num = $k2;
                foreach($data as $k3=>$v3) {
                    $total_num = (isset($v3[$page_type][$step_num])) ? $total_num+$v3[$page_type][$step_num] : $total_num;
                }
                //$body_list .= '<td>'.number_format($total_num).'</td>';
                $num_replace = $num_replace_pre.$num_i;
                $$num_replace = (isset($$num_replace)) ? $$num_replace+$total_num : $total_num;
                $num_i++;
            }
        }

        $body_list .= '</tr> ';
        //replace the region total.
        foreach($tmp_num_arr as $k=>$num_list) {
            $replace_before = strtoupper("{".$num_replace_pre.$k."}");
            $replace_after = number_format($$num_list);
            $body_list = str_replace($replace_before,$replace_after,$body_list);
        }        

        return $body_list;
    }

    //set main body for sign up
    private function setMainBodyListForSignUpByCountry($data, $country_code) {
        $body = '<table width="100%" border="0" class="tb1">'.
                    self::setTableHeaderTitle().
                    $this->setTableBody($data,$country_code).
                '</table>';
        return $body;
    }

    //set main body for sign up by none--without parameter
    private function setMainBodyListForSignUpByNone($data) {
        $body = null;
        $body .= '<table width="100%" border="0" class="tb1">'.
                 self::setTableHeaderTitleByNone().
                 $this->setTableBodyByNone($data).
                 '</table>';
        return $body;
    }

    //set data's structure.
    private function setDataParameter($countries_code) {
        $data = array();
        foreach($countries_code as $region=>$region_val) {
            foreach($region_val as $code=>$name) {
                $data[$code] = array();
            }
        }
        return $data;
    }

    private function setBlankLineWithMessage($flag,$message=null) {
        $tmp_title = ($flag) ? AC::VIDEO_VIEWING_REPORT_REGION_COUNTRY_GROUP : AC::VIDEO_VIEWING_REPORT_TOTAL_SUMMARY;
        $message = (!empty($message)) ? $message : ErrorMessage::HAVE_NO_DATA;
        $body = '<table border="0" width="100%" colspacing="0" cellpadding="0" >'.
                '   <tr><td class="tit" colspan="5"><div align="center"><strong>'.$tmp_title.'</strong></div></td></tr>'.
                '   <tr height="60"><td colspan="5" align="center">'.$message.'</td></tr>'.
                '</table>';
        return $body;
    }


    //get the sign up data 
    private function getSignUpDiagnosticData($date_condition,$countries_code=array()) {
        $data = array();
        $country_group_condition = null;
        foreach($countries_code as $key=>$value) {
            $value_ = array_keys($value);
            $country_group_condition .= "'".implode("','",$value_)."',";
        }

        if (!empty($country_group_condition)) {
            $country_group_condition = ' AND country_code IN ( '.substr($country_group_condition,0,strlen($country_group_condition)-1).' )';
        }

        $condition = $date_condition.$country_group_condition;
        $obj = new ModelReportPages();
        $data = $obj->getRegionAndCountryGroupForSignUp($condition);
        return $data;
    }

    //set the body string.
    private function setSignUpDiagnosticBodyString($conditions) {
        $body = null;
        $condition = array();
        $region_country_body = null;
        $condition = $conditions['condition'];
        $tmp_date_arr = $this->getDateCondition($condition['play_time']);
        $date_condition = $tmp_date_arr['condition'];
        $countries_code = AC::getInstance()->getCountryCodesListByRegion($condition['country_code']);
        if (!empty($condition['country_code'])) {
            $data = $this->getSignUpDiagnosticData($date_condition,$countries_code);
            if (!empty($data)) {
                $region_country_body .= $this->setParagraphTitle(AC::VIDEO_VIEWING_REPORT_REGION_COUNTRY_GROUP);
                $region_country_body .= $this->setMainBodyListForSignUpByCountry($data,$countries_code);
            }
            else {
                $region_country_body = $this->setBlankLineWithMessage(1);
            }
        }
        else {
            //without parameter
            $data = $this->getSignUpDiagnosticData($date_condition);
            if (!empty($data)) {
                $region_country_body .= $this->setParagraphTitle(AC::VIDEO_VIEWING_REPORT_TOTAL_SUMMARY);
                $region_country_body .= $this->setMainBodyListForSignUpByNone($data);
            }
            else {
                $region_country_body = $this->setBlankLineWithMessage(0);
            }
        }

        return $region_country_body;
    }

    //entrance.
    protected function __renderHead() {
        $body_string = null;
        $rand_code = rand(10000,99999);
        
        //parameters re-assignment.
        $conditions = $_GET;
        $conditions['country_code'] = $conditions['country'];
        $conditions = $this->getPageCondition($conditions);

        //get the header string.
        $head_string = $this->setHeadString($conditions['condition'],null,$rand_code);
        
        //body string.
        $body_string .= $this->setSignUpDiagnosticBodyString($conditions);

        //write a tmp file Export Tool.
        $export_html_string = $this->getOutPutBody($head_string['export'],$body_string);
        $write_result = AC::getInstance()->writeTempBodyToFile($rand_code,$export_html_string);
        
        //output.
        $this->contents =$this->getOutPutBody($head_string['view'],$body_string);  
    }

}
?>